package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.example.demo.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.port}")
    private String port;

    private static final String ip = "http://localhost";


    /*上传接口 image*/
    @PostMapping("/upload/image")
    public Result<?> upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/image/" + flag + '_' + originalFilename;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        return Result.success(ip+":"+port+"/files/image/"+flag);
    }

    /*上传接口 project/jpg*///传jpg和demo用
    @PostMapping("/upload/project/{projectname}/{first}")
    public Result<?> upload1(MultipartFile file,@PathVariable String projectname,@PathVariable String first) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/project/"+projectname+"/"+first+"/" + flag + '_' + originalFilename;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        return Result.success(ip+":"+port+"/files/project/"+projectname+"/"+first+"/" + flag);
    }

    /*上传接口 project/originalfile*///传其余所有文件
    @PostMapping("/upload/project/{projectname}/{first}/{second}")
    public Result<?> upload1(MultipartFile file,@PathVariable String projectname,@PathVariable String first,@PathVariable String second) throws IOException {
        String originalFilename = file.getOriginalFilename();
        //定义文件的唯一标识（前缀）
        String flag = IdUtil.fastSimpleUUID();
        String rootFilePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/project/"+projectname+"/"+first+"/"+second+"/" + flag + '_' + originalFilename;
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        return Result.success(ip+":"+port+"/files/project/"+projectname+"/"+first+"/"+first+"/" + flag);
    }


    /**
     * 下载接口
     * @param flag
     * @param response
     */
    @GetMapping("/image/{flag}")
    public void getFiles(@PathVariable String flag,HttpServletResponse response){
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/image/";  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    @GetMapping("/project/{projectname}/{first}/{flag}")
    public void getFiles(@PathVariable String flag,@PathVariable String projectname,@PathVariable String first,HttpServletResponse response){
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/project/"+projectname+"/"+first;  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }

    @GetMapping("/project/{projectname}/{first}/{second}/{flag}")
    public void getFiles(@PathVariable String flag,@PathVariable String projectname,@PathVariable String first,@PathVariable String second,HttpServletResponse response){
        OutputStream os;  // 新建一个输出流对象
        String basePath = System.getProperty("user.dir") + "/springboot/src/main/resources/files/project/"+projectname+"/"+first +"/" + second;  // 定于文件上传的根路径
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }
}
